import re
from flask import request
from flask_shop.user import user_bp, user_api
from flask_shop import models, db
from flask_restful import Resource, reqparse
from flask_shop.utils.message import to_dict_msg
from flask_shop.utils.tokens import generate_auth_token, verify_auth_token, login_required


@user_bp.route('/')
def index():
    return 'User hello!'


class User(Resource):
    def get(self):
        try:
            id = int(request.args.get('id').strip())
            usr = models.User.query.filter_by(id = id).first()
            if usr:
                return to_dict_msg(200, usr.to_dict(), '获取用户成功')
            else:
                return to_dict_msg(200, [], '没有此用户')
        except Exception as e:
            return to_dict_msg(10000)

    def post(self):
        name = request.form.get('name')
        pwd = request.form.get('pwd')
        real_pwd = request.form.get('real_pwd')
        nickname = request.form.get('nickname')
        phone = request.form.get('phone', '')
        email = request.form.get('email', '')

        # 验证数据的完整性
        if not all([name, pwd, real_pwd]):
            return to_dict_msg(10000)

        if len(name) < 2:
            return to_dict_msg(10011)

        if len(pwd) < 2:
            return to_dict_msg(10012)

        if pwd != real_pwd:
            return to_dict_msg(10013)

        if not re.match(r'1[3456789]\d{9}', phone):
            return to_dict_msg(10014)

        if not re.match(r'^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$', email):
            return to_dict_msg(10015)

        try:
            role_id = int(request.form.get('role_name').strip()) if request.form.get('role_name') else 0
            user = models.User(name=name, password=pwd, phone=phone, email=email, nickname=nickname, role_id=role_id)
            db.session.add(user)
            db.session.commit()
            return to_dict_msg(200, msg='注册成功')
        except Exception as e:
            print(e)
            return to_dict_msg(20000)

    def put(self):
        try:
            id = int(request.form.get('id').strip())
            email = request.form.get('email').strip() if request.form.get('email') else ''
            phone = request.form.get('phone').strip() if request.form.get('phone') else ''
            role_id = int(request.form.get('role_name').strip()) if request.form.get('role_name') else 0
            usr = models.User.query.get(id)
            if usr:
                usr.email = email
                usr.phone = phone
                usr.role_id = role_id
                db.session.commit()
                return to_dict_msg(200, msg='修改用户数据成功')
            else:
                return to_dict_msg(10018)
        except Exception as e:
            print(e)
            return to_dict_msg(10000)

    def delete(self):
        try:
            id = int(request.form.get('id').strip())
            usr = models.User.query.get(id)
            if usr:
                db.session.delete(usr)
                db.session.commit()
                return to_dict_msg(200, msg='删除成功')
            else:
                return to_dict_msg(10019)
        except Exception as e:
            print(e)
            return to_dict_msg(10000)


class UserListView(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str)
        parser.add_argument('pnum', type=int)
        parser.add_argument('psize', type=int)
        try:
            args = parser.parse_args()
            name = args.get('name')
            pnum = args.get('pnum') if args.get('pnum') else 1
            psize = args.get('psize') if args.get('psize') else 2
            if name:
                users_p = models.User.query.filter(models.User.name.like('%{}%'.format(name))).paginate(page=pnum, per_page=psize)
            else:
                users_p = models.User.query.paginate(page=pnum, per_page=psize)

            data = {
                'pnum': pnum,
                'totalPages': users_p.total,
                'users': [u.to_dict() for u in users_p.items]
            }
            return to_dict_msg(200, data=data, msg='获取用户列表成功')
        except Exception as e:
            print(e)
            return to_dict_msg(10000)


@user_bp.route('/login', methods=['POST'])
# @login_required
def login():
    name = request.form.get('name')
    pwd = request.form.get('pwd')

    if not all([name, pwd]):
        return {'status': 10000, 'msg': '数据不完整'}
    if len(name) > 1:
        user = models.User.query.filter_by(name=name).first()
        if user:
            if user.check_password(pwd):
                token = generate_auth_token(user.id, 3600)
                # verify_token = verify_auth_token(token)
                # print(verify_token)
                return {'status': 200, 'msg': '登录成功', 'data': {'token': token}}
    return {'status': 10001, 'msg': '用户名或密码错误'}


@user_bp.route('/reset', methods=['GET'])
def reset_user():
    try:
        id = int(request.args.get('id'))
        usr = models.User.query.get(id)
        if usr:
            usr.password = '123456'
            db.session.commit()
            return to_dict_msg(200, msg='重置密码成功')
    except Exception as e:
        print(e)
        return to_dict_msg(20000)


@user_bp.route('/test')
@login_required
def test_user():
    return {'status': 200, 'msg': 'OK'}


user_api.add_resource(User, '/user')
user_api.add_resource(UserListView, '/user_list')
